<?php

namespace App\Admin\Actions;

use App\Models\Client;
use App\Models\User;
use Encore\Admin\Actions\BatchAction;
use Encore\Admin\Actions\Response;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Del extends BatchAction
{
    /**
     * @return array|null|string
     */
    public $name = '删除';

    /**
     * @param Model $model
     *
     * @return Response
     */
    public function handle(Collection $collection,Request $request)
    {
        $trans = [
            'failed'    => trans('admin.delete_failed'),
            'succeeded' => trans('admin.delete_succeeded'),
        ];
        $ids = [];
        foreach ($collection as $model){
            array_push($ids,$model['id']);
        }

        $user = Client::query()->whereIn('id',$ids)->whereIn('real_finished',[1,3])->exists();
        if($user){
            return $this->response()->error($trans['failed'] .' : 审核中和审核通过的客户不可删除')->refresh();
        }

        try {
            DB::transaction(function () use ($model) {
                $model->delete();
            });
        } catch (\Exception $exception) {
            return $this->response()->error("{$trans['failed']} : {$exception->getMessage()}");
        }

        return $this->response()->success($trans['succeeded'])->refresh();
    }

    /**
     * @return void
     */
    public function dialog()
    {
        $this->question(trans('admin.delete_confirm'), '', ['confirmButtonColor' => '#d33']);
    }
}
